import { Player, Position, BOARD_SIZE, DIRECTIONS } from '../types/game';

// 快速AI - 优化版本
// 开局库
const OPENING_BOOK: Position[] = [
  { row: 7, col: 7 }, // 中心点
  { row: 7, col: 6 }, // 右中心
  { row: 7, col: 8 }, // 左中心
  { row: 6, col: 7 }, // 上中心
  { row: 8, col: 7 }, // 下中心
];

// 简化的位置权重
const getPositionWeight = (row: number, col: number): number => {
  const center = Math.floor(BOARD_SIZE / 2);
  const distanceFromCenter = Math.abs(row - center) + Math.abs(col - center);
  const maxDistance = center * 2;
  return Math.max(0, maxDistance - distanceFromCenter);
};

// 简化的模式检查 - 只检查几个关键位置
const checkQuickPattern = (board: Player[][], row: number, col: number, player: Player): number => {
  if (board[row][col] !== null) return 0;
  
  let score = 0;
  
  // 检查每个方向上的连续棋子
  for (const { dr, dc } of DIRECTIONS) {
    let count = 1; // 包括当前假设下的位置
    
    // 正方向计数
    for (let i = 1; i < 5; i++) {
      const newRow = row + dr * i;
      const newCol = col + dc * i;
      if (newRow >= 0 && newRow < BOARD_SIZE && 
          newCol >= 0 && newCol < BOARD_SIZE && 
          board[newRow][newCol] === player) {
        count++;
      } else {
        break;
      }
    }
    
    // 反方向计数
    for (let i = 1; i < 5; i++) {
      const newRow = row - dr * i;
      const newCol = col - dc * i;
      if (newRow >= 0 && newRow < BOARD_SIZE && 
          newCol >= 0 && newCol < BOARD_SIZE && 
          board[newRow][newCol] === player) {
        count++;
      } else {
        break;
      }
    }
    
    // 简化的评分系统
    if (count >= 5) {
      score += 100000; // 五子连珠
    } else if (count === 4) {
      // 检查是否有阻挡
      const leftRow = row - dr * count;
      const leftCol = col - dc * count;
      const rightRow = row + dr * 5;
      const rightCol = col + dc * 5;
      
      const leftBlocked = leftRow < 0 || leftRow >= BOARD_SIZE || 
                         leftCol < 0 || leftCol >= BOARD_SIZE || 
                         board[leftRow][leftCol] !== null;
      const rightBlocked = rightRow < 0 || rightRow >= BOARD_SIZE || 
                          rightCol < 0 || rightCol >= BOARD_SIZE || 
                          board[rightRow][rightCol] !== null;
      
      if (!leftBlocked || !rightBlocked) {
        score += 50000; // 活四
      } else {
        score += 5000; // 冲四
      }
    } else if (count === 3) {
      score += 1000; // 三子
    } else if (count === 2) {
      score += 100; // 两子
    }
  }
  
  // 添加位置权重
  score += getPositionWeight(row, col) * 10;
  
  return score;
};

// 快速获胜检查
const checkImmediateWin = (board: Player[][], row: number, col: number, player: Player): boolean => {
  for (const { dr, dc } of DIRECTIONS) {
    let count = 1;
    
    // 正方向
    for (let i = 1; i < 5; i++) {
      const newRow = row + dr * i;
      const newCol = col + dc * i;
      if (newRow >= 0 && newRow < BOARD_SIZE && 
          newCol >= 0 && newCol < BOARD_SIZE && 
          board[newRow][newCol] === player) {
        count++;
      } else {
        break;
      }
    }
    
    // 反方向
    for (let i = 1; i < 5; i++) {
      const newRow = row - dr * i;
      const newCol = col - dc * i;
      if (newRow >= 0 && newRow < BOARD_SIZE && 
          newCol >= 0 && newCol < BOARD_SIZE && 
          board[newRow][newCol] === player) {
        count++;
      } else {
        break;
      }
    }
    
    if (count >= 5) {
      return true;
    }
  }
  return false;
};

// 获取简化的候选位置（只考虑棋子周围1格）
const getQuickCandidateMoves = (board: Player[][]): Position[] => {
  const candidates: Position[] = [];
  const visited = new Set<string>();
  
  // 收集已有棋子周围的空位
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] !== null) {
        // 只在已有棋子周围1格范围内搜索（而不是2格）
        for (let dr = -1; dr <= 1; dr++) {
          for (let dc = -1; dc <= 1; dc++) {
            if (dr === 0 && dc === 0) continue; // 跳过当前棋子
            
            const newRow = row + dr;
            const newCol = col + dc;
            const key = `${newRow}-${newCol}`;
            
            if (newRow >= 0 && newRow < BOARD_SIZE && 
                newCol >= 0 && newCol < BOARD_SIZE && 
                board[newRow][newCol] === null && 
                !visited.has(key)) {
              candidates.push({ row: newRow, col: newCol });
              visited.add(key);
            }
          }
        }
      }
    }
  }
  
  // 如果棋盘为空，返回开局库
  if (candidates.length === 0) {
    return OPENING_BOOK;
  }
  
  return candidates;
};

// 简化的快速AI
export const getFastAIMove = (board: Player[][], aiPlayer: Player): Position => {
  const opponent = aiPlayer === 'black' ? 'white' : 'black';
  
  // 第一步或第二步使用开局库
  const emptyCount = board.flat().filter(cell => cell === null).length;
  if (emptyCount >= BOARD_SIZE * BOARD_SIZE - 2) {
    return OPENING_BOOK[0];
  }
  
  // 检查是否能立即获胜
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] === null && checkImmediateWin(board, row, col, aiPlayer)) {
        return { row, col };
      }
    }
  }
  
  // 检查是否需要阻挡对手获胜
  let bestDefensiveMove: Position | null = null;
  let maxThreat = 0;
  
  const candidates = getQuickCandidateMoves(board);
  
  for (const move of candidates) {
    if (checkImmediateWin(board, move.row, move.col, opponent)) {
      return move; // 必须阻挡
    }
  }
  
  // 快速评估所有候选位置
  let bestMove = candidates[0] || { row: 7, col: 7 };
  let bestScore = -1;
  
  for (const move of candidates) {
    const score = checkQuickPattern(board, move.row, move.col, aiPlayer) - 
                 checkQuickPattern(board, move.row, move.col, opponent) * 0.8;
    
    if (score > bestScore) {
      bestScore = score;
      bestMove = move;
    }
  }
  
  return bestMove;
};